﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Inspinia_MVC5.Data;
using Inspinia_MVC5.Models;
using Webdiyer.WebControls.Mvc;

namespace Inspinia_MVC5.Controllers
{
    
    public class BorrowsController : Controller
    {
        private BooksSystemContext db = new BooksSystemContext();


        // GET: /Borrows/
        [Authorize]
        public ActionResult Index(string name,string idcard,string status,string chaoqi,int id=1)
        {
            string date = DateTime.Now.ToString("MM/dd/yyyy");
            ViewBag.Date = date;
            string start = Request["start"];
            string end = Request["end"];
            var model = db.Borrows.Include(b => b.Book).Include(b => b.Student).Include(b => b.Teacher).ToList();
            bool admin = true;
            if (Session["role"] != null && Session["role"].ToString() == "Teacher")
            {
                admin = false;
                Teacher teacher = Session["Teacher"] as Teacher;
                model = model.Where(t=>t.TeacherId==teacher.ID).ToList();
            }
            if (Session["role"] != null && Session["role"].ToString() == "Student")
            { 
                admin = false;
                Student student = Session["Student"] as Student;
                model = model.Where(t => t.StudentId == student.ID).ToList();
            }
            if (start != null && end != null)
            {
                DateTime dstart = DateTime.Parse(start);
                DateTime dend = DateTime.Parse(end);
                dend = dend.AddDays(1);
                model = model.Where(x=>x.JieYueDate>dstart&&x.JieYueDate<dend).ToList();
            }
            ViewBag.Admin = admin;
            ViewBag.Status = status;
            if (status != ""&&status!=null)
            {
                int sta = int.Parse(status);
                if (sta == 1)
                {
                    model = model.Where(x => x.Status == 1).ToList();

                }
                else if (sta == 2&&chaoqi==null)
                {
                    model = model.Where(x => x.Status == 1||x.Status==2).ToList();

                }
                else if (sta == 2 && chaoqi == "1")
                {
                    model = model.Where(x => {
                        DateTime dt1 = DateTime.Parse(x.YingHuanDate.ToString());
                        DateTime dt2 = DateTime.Now;
                        int result = (dt2 - dt1).Days;
                        bool result2 = result < 1 && result > -5;
                        if ((x.Status == 1 || x.Status == 2)&&result2) { return true; } else { return false; }
                    }).ToList();

                }
                else if (sta == 2 && chaoqi == "2")
                {
                    model = model.Where(x => {
                        DateTime dt1 = DateTime.Parse(x.YingHuanDate.ToString());
                        DateTime dt2 = DateTime.Now;
                        int result = (dt2 - dt1).Days;
                        bool result2 = result>0;
                        if ((x.Status == 1 || x.Status == 2) && result2) { return true; } else { return false; }
                    }).ToList();

                }

            }
            if (name != null)
            {
                model = model.Where(x => {
                    if (x.Teacher != null) { return x.Teacher.TeaName.Contains(name); }
                    else { return x.Student.StuName.Contains(name); }
                }).ToList();
            }
            if (idcard != null)
            {
                model = model.Where(x => {
                    if (x.Teacher != null) { return x.Teacher.TeaIdCard.Contains(idcard); }
                    else { return x.Student.StuIdCard.Contains(idcard); }
                }).ToList();

                //model = model.Where(x => x.Student.StuIdCard.Contains(idcard) || x.Teacher.TeaIdCard.Contains(idcard)).ToList();
            }
            model = model.OrderByDescending(a => a.ID).ToPagedList(id, 10);

            if (Request.IsAjaxRequest())
                return PartialView("_BorrowsList", model);
            return View(model);
            //var borrows = db.Borrows.Include(b => b.Book).Include(b => b.Student).Include(b => b.Teacher);
            //return View(borrows.ToList());
        }
        public ActionResult ZhiNaJin(string name, string idcard, string status, string chaoqi, int id = 1)
        {
            string date = DateTime.Now.ToString("MM/dd/yyyy");
            ViewBag.Date = date;
            string start = Request["start"];
            string end = Request["end"];
            var model = db.Borrows.Where(x=>x.OverDue!=null).Include(b => b.Book).Include(b => b.Student).Include(b => b.Teacher).ToList();
            bool admin = true;
            //if (Session["role"] != null && Session["role"].ToString() == "Teacher")
            //{
            //    admin = false;
            //    Teacher teacher = Session["Teacher"] as Teacher;
            //    model = model.Where(t => t.TeacherId == teacher.ID).ToList();
            //}
            //if (Session["role"] != null && Session["role"].ToString() == "Student")
            //{
            //    admin = false;
            //    Student student = Session["Student"] as Student;
            //    model = model.Where(t => t.StudentId == student.ID).ToList();
            //}
            if (start != null && end != null)
            {
                DateTime dstart = DateTime.Parse(start);
                DateTime dend = DateTime.Parse(end);
                dend = dend.AddDays(1);
                model = model.Where(x => x.JieYueDate > dstart && x.JieYueDate < dend).ToList();
            }
            ViewBag.Admin = admin;
            //ViewBag.Status = status;
            //if (status != "" && status != null)
            //{
            //    int sta = int.Parse(status);
            //    if (sta == 1)
            //    {
            //        model = model.Where(x => x.Status == 1).ToList();

            //    }
            //    else if (sta == 2 && chaoqi == null)
            //    {
            //        model = model.Where(x => x.Status == 1 || x.Status == 2).ToList();

            //    }
            //    else if (sta == 2 && chaoqi == "1")
            //    {
            //        model = model.Where(x => {
            //            DateTime dt1 = DateTime.Parse(x.YingHuanDate.ToString());
            //            DateTime dt2 = DateTime.Now;
            //            int result = (dt2 - dt1).Days;
            //            bool result2 = result < 1 && result > -5;
            //            if ((x.Status == 1 || x.Status == 2) && result2) { return true; } else { return false; }
            //        }).ToList();

            //    }
            //    else if (sta == 2 && chaoqi == "2")
            //    {
            //        model = model.Where(x => {
            //            DateTime dt1 = DateTime.Parse(x.YingHuanDate.ToString());
            //            DateTime dt2 = DateTime.Now;
            //            int result = (dt2 - dt1).Days;
            //            bool result2 = result > 0;
            //            if ((x.Status == 1 || x.Status == 2) && result2) { return true; } else { return false; }
            //        }).ToList();

            //    }

            //}
            if (name != null)
            {
                model = model.Where(x =>
                {
                    if (x.Teacher != null) { return x.Teacher.TeaName.Contains(name); }
                    else { return x.Student.StuName.Contains(name); }
                }).ToList();
            }
            if (idcard != null)
            {
                model = model.Where(x =>
                {
                    if (x.Teacher != null) { return x.Teacher.TeaIdCard.Contains(idcard); }
                    else { return x.Student.StuIdCard.Contains(idcard); }
                }).ToList();

                //model = model.Where(x => x.Student.StuIdCard.Contains(idcard) || x.Teacher.TeaIdCard.Contains(idcard)).ToList();
            }
            model = model.OrderByDescending(a => a.ID).ToPagedList(id, 5);

            if (Request.IsAjaxRequest())
                return PartialView("_BorrowsList", model);
            return View(model);
            //var borrows = db.Borrows.Include(b => b.Book).Include(b => b.Student).Include(b => b.Teacher);
            //return View(borrows.ToList());
        }

        public ActionResult Renew(int?id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Borrow borrow = db.Borrows.Find(id);
            if (borrow == null)
            {
                return HttpNotFound();
            }
            return View(borrow);

        }
        [HttpPost]
        public ActionResult Renew(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Borrow borrow = db.Borrows.Find(int.Parse(id));
            if (borrow == null)
            {
                return HttpNotFound();
            }
            borrow.XuJieDate = DateTime.Now;
            borrow.YingHuanDate = DateTime.Now.AddMonths(1);
            borrow.Status = 2;
            db.SaveChanges();
            return RedirectToAction("Index");

        }
        [AdminAuthorize]
        public ActionResult Back(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Borrow borrow = db.Borrows.Find(id);
            if (borrow == null)
            {
                return HttpNotFound();
            }
            DateTime dt1 = DateTime.Parse(borrow.YingHuanDate.ToString());
            DateTime dt2 = DateTime.Now;
            int result = (dt2 - dt1).Days;
            if (result >0)
            {
                ViewBag.YuQi = result;
                borrow.OverDue = borrow.Book.BookOverdue * result;
            }
            return View(borrow);

        }
        [HttpPost]
        [AdminAuthorize]
        public ActionResult Back(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Borrow borrow = db.Borrows.Find(int.Parse(id));
            if (borrow == null)
            {
                return HttpNotFound();
            }
            borrow.ReturnDate = DateTime.Now;
            borrow.Status = 3;
            DateTime dt1 = DateTime.Parse(borrow.YingHuanDate.ToString());
            DateTime dt2 = DateTime.Now;
            int result = (dt2 - dt1).Days;
            if (result > 0)
            {
                borrow.OverDue = borrow.Book.BookOverdue * result;
            }
            var book = db.Books.SingleOrDefault(x => x.ID == borrow.BookId);
            book.BookNum += 1;
            db.SaveChanges();
            return RedirectToAction("Index");

        }
        public ActionResult GetUesr(string seaType,string text,string role)
        {
            if(role=="0")
            {
                var model = db.Teachers.ToList();
                if(seaType=="0")
                {
                    model = model.Where(x=>x.TeaName.Contains(text)).ToList();
                }
                else
                {
                    model = model.Where(x => x.TeaIdCard.Contains(text)).ToList();
                }
                model = model.Take(5).ToList();
                return PartialView("_PartialTeacher",model);

            }
            else
            {
                var model = db.Students.ToList();
                if (seaType == "0")
                {
                    model = model.Where(x => x.StuName.Contains(text)).ToList();
                }
                else
                {
                    model = model.Where(x => x.StuIdCard.Contains(text)).ToList();
                }
                model = model.Take(5).ToList();
                return PartialView("_PartialStudent", model);
            }
            
        }

        // GET: /Borrows/Details/5
        [AdminAuthorize]
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Borrow borrow = db.Borrows.Find(id);
            if (borrow == null)
            {
                return HttpNotFound();
            }
            return View(borrow);
        }

        // GET: /Borrows/Create
        [AdminAuthorize]
        public ActionResult Create(int? id)
        {
            if(id==null)
            {
                return RedirectToAction("Borrow", "Books");
            }
            Book book = db.Books.SingleOrDefault(x=>x.ID==id);
            if (book == null)
            {
                return RedirectToAction("Borrow", "Books");
            }
            ViewBag.Book = book;
            ViewBag.BookId = new SelectList(db.Books, "ID", "BookName");
            ViewBag.StudentId = new SelectList(db.Students, "ID", "StuName");
            ViewBag.TeacherId = new SelectList(db.Teachers, "ID", "TeaName");
            return View();
        }

        // POST: /Borrows/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AdminAuthorize]
        public ActionResult Create([Bind(Include="ID,BookId,Role,TeacherId,StudentId,Status,JieYueDate,YingHuanDate,ReturnDate,OverDue,XuJieDate")] Borrow borrow)
        {
            borrow.JieYueDate = DateTime.Now;
            borrow.YingHuanDate = DateTime.Now.AddMonths(1);
            borrow.Status = 1;
            if (borrow.BookId!=null&&borrow.Role!=null)
            {
               
                db.Borrows.Add(borrow);
                var book = db.Books.SingleOrDefault(x=>x.ID==borrow.BookId);
                if (book.BookJieYueLiang == null)
                {
                    book.BookJieYueLiang = 1;
                }
                else
                {
                    book.BookJieYueLiang = book.BookJieYueLiang + 1;
                }
                book.BookNum = book.BookNum - 1;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return RedirectToAction("Create");
        }

        // GET: /Borrows/Edit/5
        [AdminAuthorize]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Borrow borrow = db.Borrows.Find(id);
            if (borrow == null)
            {
                return HttpNotFound();
            }
            ViewBag.BookId = new SelectList(db.Books, "ID", "BookName", borrow.BookId);
            ViewBag.StudentId = new SelectList(db.Students, "ID", "StuName", borrow.StudentId);
            ViewBag.TeacherId = new SelectList(db.Teachers, "ID", "TeaName", borrow.TeacherId);
            return View(borrow);
        }

        // POST: /Borrows/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AdminAuthorize]
        public ActionResult Edit([Bind(Include="ID,BookId,Role,TeacherId,StudentId,Status,JieYueDate,YingHuanDate,ReturnDate,OverDue,XuJieDate")] Borrow borrow)
        {
            if (ModelState.IsValid)
            {
                db.Entry(borrow).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.BookId = new SelectList(db.Books, "ID", "BookName", borrow.BookId);
            ViewBag.StudentId = new SelectList(db.Students, "ID", "StuName", borrow.StudentId);
            ViewBag.TeacherId = new SelectList(db.Teachers, "ID", "TeaName", borrow.TeacherId);
            return View(borrow);
        }

        // GET: /Borrows/Delete/5
        [AdminAuthorize]
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Borrow borrow = db.Borrows.Find(id);
            if (borrow == null)
            {
                return HttpNotFound();
            }
            return View(borrow);
        }

        // POST: /Borrows/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [AdminAuthorize]
        public ActionResult DeleteConfirmed(int id)
        {
            Borrow borrow = db.Borrows.Find(id);
            db.Borrows.Remove(borrow);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
